package com.jindun.paper.service.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.hibernate.Hibernate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jindun.paper.dao.UserRepository;
import com.jindun.paper.model.Users;
import com.jindun.paper.service.UserService;

@Service
public class UserServiceImpl implements UserService {

	@Autowired
	private UserRepository userRepository;
	@Autowired
	private EntityManager entityManager;
	
	
	@Override
	public List<Users> findAll() {
		
		List<Users>  usersList =  this.userRepository.findAll();
		Hibernate.initialize(usersList);
		
		return usersList;
	}

	@Override
	public Users getOne(Integer userId) {
		Users user = userRepository.getOne(userId);
		Hibernate.initialize(user);
		return user;
	}

	@Override
	public boolean isUsernameUnique(Integer userId, String username) {
		
		StringBuilder jql = new StringBuilder();
		jql.append("from Users u where u.username = ? ");
		if (userId != null) {
			jql.append(" and u.id != ?");
		}
		
		Query query = this.entityManager.createQuery(jql.toString());
		query.setParameter(1, username);
		
		if (userId != null) {
			query.setParameter(2, userId);
		}
		
		return query.getResultList().size() == 0;
	
	}
	
	
	

}
